<template>
  <main-layout
    title="管理采购单"
    :showHome="true"
    :showNew="true"
    @newEvent="tonewPage"
  >
    <div class="page-container">
      <header>
        <input type="text" placeholder="输入项目名称进行查询" />
        <van-dropdown-menu class="purchase-dropdown">
          <van-dropdown-item
            v-model="purchaseList.state"
            :options="stateList"
          />
        </van-dropdown-menu>
        <i class="icon"></i>
      </header>
      <section>
        <ul class="list-box" @scroll="scrollEvt">
          <van-swipe-cell class="list-item" v-for="item in list" :key="item.id">
            <template #left>
              <van-button
                @click="
                  $router.push({
                    path: '/purchase/detail',
                    query: { id: item.id },
                  })
                "
                square
                type="primary"
                text="详情"
                class="myBtn detailBtn"
              />
            </template>

            <span class="title"
              >{{ item.projectName }}
              <em v-if="!(item.state === '作废')">{{ item.state }}</em>
              <i v-if="item.state === '作废'"
                ><img src="../../images/zf.png" alt=""
              /></i>
            </span>
            <span>创建人: {{ item.createName }}</span>
            <span>创建日期: {{ item.createTime | df("yyyy-MM-dd") }}</span>
            <span
              >材料:
              {{
                `${item.materialName}--${item.materialWeight} ${item.materialUnit}`
              }}</span
            >
            <template #right>
              <van-button
                v-if="item.state === '新建'"
                square
                type="danger"
                text="删除"
                @click="purchaseDeleteEvt(item)"
                class="myBtn"
              />
              <van-button
                v-if="item.state === '新建'"
                square
                type="warning"
                text="编辑"
                class="myBtn"
                @click="tonewPage(item)"
              />
              <van-button
                v-if="item.state === '新建'"
                square
                color="#ff5b02"
                text="确认"
                class="myBtn"
                @click="approveEvt(item)"
              />
              <van-button
                v-if="item.state === '确认'"
                square
                color="#ff5b02"
                text="在途"
                class="myBtn"
                @click="approveEvt(item)"
              />
              <van-button
                v-if="item.state === '在途'"
                square
                color="#ff5b02"
                text="完成"
                class="myBtn"
                @click="approveEvt(item)"
              />
              <van-button
                v-if="item.state === '完成'"
                square
                color="rgb(180, 9, 223)"
                text="收款"
                class="myBtn"
              />
            </template>
          </van-swipe-cell>
          <li>
            <span v-if="loading" class="more">加载中...</span>
            <span v-if="!loading && hasMore" class="more"
              >向下滑动加载更多...</span
            >
            <span v-if="!loading && !hasMore" class="more"
              >不要再划了，木有了!</span
            >
          </li>
        </ul>
      </section>
    </div>
    <!-- 弹出处理意见框 -->
    <van-popup
      v-model="approveShow"
      round
      position="bottom"
      :style="{ height: '50%', width: '100%' }"
    >
      <van-steps :active="active" active-icon="success" active-color="#ff5b02">
        <van-step v-for="item in stepList" :key="item.text">{{
          item.value
        }}</van-step>
      </van-steps>

      <van-form @submit="onSubmit">
        <!-- 基本信息 -->
        <van-field
          v-model="approveObj.userName"
          type="text"
          readonly
          :label="stepList[active].text + '处理人'"
        />
        <van-field name="radio" label="是否同意">
          <template #input>
            <van-radio-group
              v-model="approveObj.isReject"
              direction="horizontal"
            >
              <van-radio :name="false" checked-color="#ff5b02">通过</van-radio>
              <van-radio :name="true" checked-color="#ff5b02">驳回</van-radio>
            </van-radio-group>
          </template>
        </van-field>
        <!-- 单选框 -->

        <!-- 备注信息 -->
        <van-field
          v-model="approveObj.remark"
          type="textarea"
          autosize
          label="备注"
          placeholder="请输入备注"
          :rules="[{ required: true, message: '输入审批意见' }]"
        />

        <div style="margin: 12px 8px">
          <van-button
            round
            block
            type="info"
            native-type="submit"
            color="#ff5b02"
            >提交</van-button
          >
        </div>
      </van-form>
    </van-popup>
  </main-layout>
</template>
<script>
import { Dialog } from "vant";
import {
  purchaseListApi,
  purchaseFlowApi,
  purchaseDeleteApi,
} from "../../apis/PurchaseApi";
const stepList = [
  { text: "新建", value: "新建" },
  { text: "确认", value: "确认" },
  { text: "在途", value: "在途" },
  { text: "完成", value: "完成" },
];
export default {
  data() {
    return {
      approveShow: false,
      stepList,
      stateList: [
        { text: "全部", value: "" },
        ...stepList,
        { text: "作废", value: "作废" },
      ],
      approveObj: {
        id: "",
        isReject: false,
        userId: "",
        userName: "",
        remark: "",
      },
      approveState: "",
      purchaseList: {
        projectName: "",
        state: "",
        page: 1,
        size: 6,
      },
      list: [],
      // 是否在加载中
      loading: true,
      // 定义为是否后端还有数据的标识
      hasMore: true,
    };
  },
  created() {
    this.getList();
  },
  computed: {
    userInfo() {
      return this.$store.getters["common/userInfomation"];
    },
    active() {
      return this.stepList.findIndex((it) => it.text === this.approveState) + 1;
    },
    userRight() {
      return this.$store.getters["common/userRights"];
    },
  },
  methods: {
    tonewPage(row) {
      // 判断是新增事件还是编辑事件
      let edit = !!row;
      // 判断是否有进去的权限
      let right = this.userRight.find((it) => it.id === "PURCHASE-01-01");
      if (!!right) {
        // 有进去的权限
        if (!edit && right.role.includes("C")) {
          this.$router.push({
            name: "editPurchase",
            query: { from: "list" },
          });
        } else {
          // 是从编辑按钮过来
          if (!!edit) {
            // 判断是否有进去的权限
            if (right.role.includes("C")) {
              this.$router.push({
                name: "editPurchase",
                query: { id: row.id, from: "list" },
                params: { row },
              });
            } else {
              this.$toast.fail("您没有访问的权限!");
            }
          } else {
            this.$toast.fail("您没有访问的权限!");
          }
        }
      } else {
        this.$toast.fail("您没有访问的权限!");
      }
    },
    // 提交审批
    async onSubmit() {
      let result = await purchaseFlowApi(this.approveObj);
      let stateIndex = this.active;
      if (result.code === 200) {
        // 审批提交成功，获取数据，找到对应数据
        this.$toast.success(`审批${this.stepList[stateIndex].text}成功!`);
        // 如果审批点击的是通过
        if (!this.approveObj.isReject) {
          this.list.map((it) => {
            if (it.id === this.approveObj.id) {
              // 改变显示状态
              it.state = this.stepList[stateIndex].value;
            }
          });
        } else {
          // 点击了驳回，则状态退回一步
          let idx = this.list.findIndex((it) => it.id === this.approveObj.id);
          let nowidx = stateIndex - 2;
          // 改变显示状态
          this.list[idx].state = this.stepList[nowidx >= 0 ? nowidx : 0].value;
        }
        this.approveShow = false;
      } else {
        this.$toast.fail(`审批${this.stepList[stateIndex].text}失败!`);
      }
    },
    scrollEvt(e) {
      // 是否已经滚动到底部
      let bottom =
        e.target.scrollHeight -
          e.target.offsetHeight -
          e.target.scrollTop -
          20 <
        0;
      if (bottom && this.hasMore && !this.loading) {
        // 将滑动状态改为true
        this.loading = true;
        // 加载下一页数据
        this.purchaseList.page += 1;
        // 调用数据请求方法
        this.getList();
      }
    },
    async getList() {
      let result = await purchaseListApi(this.purchaseList);
      if (result.code === 200) {
        this.list = this.list.concat(result.data.rows);
        // 计算hasMore的值：当前页树 * 每页展示的条数 要小于 后端总条数 才有更多数据，还没有从后端获取回来
        this.hasMore =
          this.purchaseList.page * this.purchaseList.size < result.data.total;
      }
      setTimeout(() => {
        this.loading = false;
      });
    },
    purchaseDeleteEvt(item) {
      Dialog.confirm({
        title: "删除提示",
        message: "确认要删除这条信息？",
      })
        .then(async () => {
          let result = await purchaseDeleteApi(item.id);
          if (result.code === 200) {
            history.go(0);
            this.$toast.success("删除成功!");
          } else {
            this.$toast.fail("删除失败!");
          }
        })
        .catch(() => {});
    },
    approveEvt(item) {
      // 判断是否有打开弹出框的权限
      let idx = this.stepList.findIndex((it) => it.text === item.state) + 1;
      let name = this.stepList[idx].value;
      // 确认的时候需要是审批人才可以打开弹出框，创建人也不可以打开
      if (name === "确认" && !item.nextId.includes(this.userInfo.id)) {
        this.$toast.fail("对不起，您不具备确认的权限!");
        return;
      }
      // 对弹出框中的数据进行重置
      this.approveObj.id = item.id;
      this.approveObj.isReject = false;
      this.approveObj.userId = this.userInfo.id;
      this.approveObj.userName = this.userInfo.name;
      this.approveObj.remark = "";
      this.approveState = item.state;
      // 打开弹出框
      this.approveShow = true;
    },
  },
};
</script>
<style lang="less" scoped>
@import "./index.less";
</style>